package com.cabbagetofu.crowd.filter;


import com.atguigu.crowd.constant.AccessPassResource;
import com.atguigu.crowd.constant.CrowdConstant;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Component
public class CrowAccessFilter extends ZuulFilter {


    @Override
    public String filterType() {

        //"pre" 表示在目标微服务前执行过滤
        return "pre";
    }


    @Override
    public int filterOrder() {
        return 0;
    }

    // return true:表示被拦截,继续执行下面的run方法; false: 表示放行
    @Override
    public boolean shouldFilter() {

        // 通过getCurrentContext得到当前的RequestContext
        RequestContext requestContext = RequestContext.getCurrentContext();

        // 通过RequestContext得到HttpServletRequest
        HttpServletRequest request = requestContext.getRequest();

        // 获取当前的请求路径
        String servletPath = request.getServletPath();

        // 判断当前请求路径是否包含在不被过滤的请求的set集合中
        boolean isPassContains = AccessPassResource.PASS_RES_SET.contains(servletPath);

        // 如果包含，返回false，表示不会被过滤
        if (isPassContains){

            return false;
        }

        // 判断当前的请求路径中是否包含不被过滤的资源
        boolean isStaticResource = AccessPassResource.judgeIsStaticResource(servletPath);

        // 是静态资源则工具方法返回true，因为应该放行，所以取反，返回false
        return !isStaticResource;
    }

    // 具体需要执行哪些过滤的方法
    @Override
    public Object run() throws ZuulException {

        // 获取request对象
        RequestContext requestContext = RequestContext.getCurrentContext();
        HttpServletRequest request = requestContext.getRequest();

        // 根据session获取登录对象
        HttpSession session = request.getSession();
        Object loginMember = session.getAttribute(CrowdConstant.ATTR_NAME_LOGIN_MEMBER);

        if (loginMember == null){

            // 提示用户登录后在访问
            session.setAttribute(CrowdConstant.ATTR_NAME_MESSAGE, CrowdConstant.MESSAGE_ACCESS_FORBIDEN);

            // 重定向至登录页面
            HttpServletResponse response = requestContext.getResponse();
            try {
                response.sendRedirect("/auth/member/to/login/page");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }
}
